package com.xmy.cultivate.controller;


import com.xmy.cultivate.entity.Admin;
import com.xmy.cultivate.entity.Company;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.enums.StatusStaffEnum;
import com.xmy.cultivate.service.ICompanyService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import com.xmy.cultivate.util.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录账号 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    ICompanyService iCompanyService;


    @PostMapping(value = "")
    public Result login(@RequestBody Map<String,Object> reMap){
        //构造登录令牌
        try {
            /**
             * 密码加密：
             *     shiro提供的md5加密
             *     Md5Hash:
             *      参数一：加密的内容
             *              111111   --- abcd
             *      参数二：盐（加密的混淆字符串）（用户登录的用户名）
             *              111111+混淆字符串
             *      参数三：加密次数
             *
             */
            String username = (String) reMap.get("username");
            String password = (String) reMap.get("password");
            //System.out.print("username:"+username);
            //System.out.println();
            //System.out.print("password:"+password);
            password = new Md5Hash(password,username,3).toString();
            //System.out.print("password:"+password);
            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
            //1.获取subject
            Subject subject = SecurityUtils.getSubject();
            //2.调用subject进行登录
            subject.login(upToken);//获取session
            String sid = (String) subject.getSession().getId();
            Map<String,Object> data = new HashMap<>();
            data.put("token",sid);

            //1.subject获取所有的安全数据集合
            PrincipalCollection principals = subject.getPrincipals();
            if(principals != null && !principals.isEmpty()){
                //2.获取安全数据
                Admin admin = (Admin) principals.getPrimaryPrincipal();
                if (admin.getIsLogin().equals(0)){
                    return new Result(Code.ERROR,"","不能登录，请与管理员联系");
                }
                Staff staffInfo = admin.getStaffInfo();
                if (staffInfo != null && staffInfo.getStatus().equals(StatusStaffEnum.OUT)){
                    return new Result(Code.ERROR,"","已离职，不能登陆");
                }
            }

            Company company = iCompanyService.getById(1L);
            if(company !=null){
                if(company.getIsMaintain() == 1){
                    if(username.equals("admin")){
                        return new Result(Code.OK,data);
                    }else{
                        return new Result(Code.ERROR,"","系统维护中……");
                    }
                }else {
                    return new Result(Code.OK,data);
                }
            }else {
                return new Result(Code.OK,data);
            }
            //System.out.println("token:"+sid);
            //return new Result(Code.OK,data);
        }catch (Exception e) {
            //return new Result(Code.ERROR,e.getMessage());
            //return new Result(Code.OK,data);
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }
    }
}
